package cn.yotta.user.web.autoconfiguration.filter;

import cn.yotta.user.web.autoconfiguration.context.header.CookieContext;
import cn.yotta.user.web.autoconfiguration.context.header.HeaderContext;
import cn.yotta.user.web.autoconfiguration.utils.CookieUtils;
import cn.yotta.user.web.autoconfiguration.utils.HeaderUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author wyaoyao
 * @date 2022/11/8 14:47
 * 当前过滤器需要在UserContextFilter之前，解析出请求中的请求头信息和cookie信息
 */
public class HeaderContextFilter implements Filter {

    /**
     * 过滤器顺序，数字越小，越先执行
     */
    public final static Integer ORDER = -10000;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            initHeaders(httpServletRequest);
            initCookies(httpServletRequest);
            chain.doFilter(request, response);
        } finally {
            CookieContext.clearCookies();
            HeaderContext.clearHeaders();
        }
    }

    private void initCookies(HttpServletRequest request) {
        CookieContext.setCookies(CookieUtils.readCookies(request));
    }

    private void initHeaders(HttpServletRequest request) {
        HeaderContext.setHeaders(HeaderUtils.readHeaders(request));
    }
}
